package com.nit.store.controller;

import com.nit.store.pojo.dto.output.CartDto;
import com.nit.store.service.CartService;
import com.nit.store.util.JwtUtils;
import com.nit.store.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * @Author J1ay
 * @Date 2022/7/21 20:12
 * @Description 购物车
 */
@RestController
@RequestMapping("/carts")
@Slf4j
public class CartController {
    @Autowired
    CartService cartService;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Autowired
    private JwtUtils jwtUtils;

    @PreAuthorize("hasAuthority('/cart/add')")
    @PostMapping("/add_to_cart")
    public JsonResult<Void> addToCart(Long pid, Long amount, @RequestHeader(value="Authentication") String token) {
        Long uid = jwtUtils.parseJwtGetId(token.substring(tokenHeader.length()));
        String username = jwtUtils.parseJwtGetName(token.substring(tokenHeader.length()));
        cartService.addToCart(pid, amount, uid, username);
        return JsonResult.ok();
    }

    @PreAuthorize("hasAuthority('/cart/update')")
    @PostMapping("/update")
    public JsonResult<Void> updateCart(Long cid, Long num, @RequestHeader(value="Authentication") String token) {
        Long uid = jwtUtils.parseJwtGetId(token.substring(tokenHeader.length()));
        cartService.updateCart(cid, num, uid);
        return JsonResult.ok();
    }

    @PreAuthorize("hasAuthority('/cart/update')")
    @PostMapping("/delFromCart")
    public JsonResult<Void> delFromCart(Long cid) {
        cartService.delFromCart(cid);
        return JsonResult.ok();
    }

    @PreAuthorize("hasAuthority('/cart/show')")
    @GetMapping("/")
    public JsonResult<CartDto[]> getCart(@RequestHeader(value="Authentication") String token) {
        Long uid = jwtUtils.parseJwtGetId(token.substring(tokenHeader.length()));
        return JsonResult.ok(cartService.getCartListByUid(uid));
    }

    @PreAuthorize("hasAuthority('/cart/show')")
    @GetMapping("/get_by_cids")
    public JsonResult<CartDto[]> getCartByCid(Long[] cids) {
        return JsonResult.ok(cartService.getCartByCid(cids));
    }
}
